<?php
declare (strict_types=1);

namespace app\admin\model\site;

use app\common\logic\Attach;
use app\common\model\BaseModel;
use Nette\Utils\Json;
use Nette\Utils\JsonException;

/**
 * Class Template
 *
 * @package app\admin\model\site
 */
class Template extends BaseModel
{
    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'template';

    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;

    /**
     * 时间显示格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';

    /**
     * 定义表主键
     *
     * @var string
     */
    protected $pk = 'id';

    // 定义全局的查询范围
    protected $globalScope = ['mhm'];

    // 数据类型转换
    protected $type = [
        'template_data' => 'array'
    ];

    public function scopeMhm($query)
    {
        if (request()->is_platform) {
            $query->whereIn('mhm_id', [request()->mhm_id, 0]);
        } else {
            $query->where('mhm_id', request()->mhm_id);
        }
    }

    /**
     * 新增数据事件
     *
     */
    public static function onBeforeInsert($data)
    {
        // 机构
        $data->mhm_id = $data->getAttr('mhm_id') ?: request()->mhm_id;
    }

    /**
     * 模板类型文字描述
     *
     * @param $value
     * @param $data
     * @return string
     */
    public function getTemplateTypeTextAttr($value, $data)
    {
        $text = [
            'mobile_home' => '手机端-首页模板',
            'pc_home'     => '电脑端-首页模板'
        ];

        $type = $data['template_type'];

        return $text[$type] ?? '未知';
    }

    /**
     * 解析模板数据
     *
     * @param $value
     * @return array|mixed
     * @throws JsonException
     */
    public function getTemplateDataAttr($value)
    {
        $templateData = is_array($value) ? $value : Json::decode($value, 1);
        foreach ($templateData as $k => $item) {
            $component = $item['component'] ?? '';
            switch ($component) {
                case 'banner':// 轮播图
                case 'advert':// 广告位
                case 'graphicNav': // 图文导航
                    // 处理图片地址
                    $sourceList = $item['setStyle']['form']['source_list'];
                    foreach ($sourceList as &$sourceItem) {
                        if (isset($sourceItem['icon_id']) && $sourceItem['icon_id']) {
                            $sourceItem['url'] = app(Attach::class)->where('id', $sourceItem['icon_id'])->findOrEmpty()->fileurl;
                        }
                    }
                    unset($sourceItem);
                    $item['setStyle']['form']['source_list'] = $sourceList;
                    $templateData[$k]                        = $item;
                    break;
            }
        }

        return $templateData;
    }

}
